import { Component, Input, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';

import { Config } from '@core/job/custom';
import { fnCheckForm, fnResteForm } from '@util/form';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-custom-config-form',
  templateUrl: './custom-config-form.component.html'
})
export class CustomConfigFormComponent implements OnInit {
  @Input() config?: Config;

  form: UntypedFormGroup;
  constructor(private fb: UntypedFormBuilder, private modal: NzModalRef) {
    this.form = this.fb.group({
      className: [null, [Validators.required]],
      methodName: [null, [Validators.required]],
      methodParams: [null],
      cronExpression: [null, [Validators.required]],
      remark: [null],
      enabled: [null, [Validators.required]]
    });
  }

  ngOnInit(): void {
    this.setValueForm();
  }

  setValueForm(): void {
    this.resetForm();
    if (this.config) {
      this.form.setValue({
        className: this.config.className,
        methodName: this.config.methodName,
        methodParams: this.config.methodParams,
        cronExpression: this.config.cronExpression,
        remark: this.config.remark,
        enabled: this.config.enabled
      });
    }
  }

  resetForm(): void {
    fnResteForm(this.form);
  }

  sure(): void {
    if (fnCheckForm(this.form)) {
      return;
    }

    this.modal.destroy(this.form.getRawValue());
  }
}
